<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    /**
     * 个人中心-修改个人信息-页面
     */
    public function infoPage()
    {
        return view('user.info');
    }

    /**
     * 个人中心-修改个人信息-更新数据
     */
    public function infoUpdate(UserRequest $request)
    {
        $name = $request->input('name');
        $email = $request->input('email');
        //获取用户id
        $id = auth()->id();
        //更新数据
        $res = DB::table('users')
            ->where('id',$id)
            ->update(['name'=>$name,'email'=>$email]);

        if($res){
            return back()->with(['success'=>'更新成功']);
        }else{
            // return back()->withErrors('未做更改');
            // return back()->with(['success'=>'更新成功']);
            return back()->with(['warning'=>'未做更改']);
        }
    }

    /**
     * 个人中心-更换头像-页面
     */
    public function avatarPage()
    {
        return view('user.avatar');
    }

    /**
     * 个人中心-更换头像-更新数据
     */
    public function avatarUpdate(Request $request)
    {
        //快速验证
        $validatedData = $request->validate([
            'avatar'=>'required|image'
        ],[
            'avatar.required'=>'请选择图片',
            'avatar.image'=>'请选择图片格式'
        ]);
       $file = $request->file('avatar');

       //获取改用户id
        $id = auth()->id();
       //指定磁盘使用public
        $path = $file->store('avatar','public');
        //获取旧文件
        $oldAvatar = auth()->user()->avatar;

        //更新头像
        $res = DB::table('users')
            ->where('id',$id)
            ->update(['avatar'=>$path]);
        if($res){
            //删除旧文件
            Storage::disk('public')->delete($oldAvatar);
            return back()->with(['success'=>'头像更新成功']);
        }else{
            return back()->withErrors('头像更新失败');
        }
    }

    /**
     * 个人中心-我的博客
     */
    public function blog()
    {
        //查询当前用户的所有博客
       $blogs = auth()->user()->blogs()->withCount('comments')->orderBy('updated_at','DESC')->paginate(3);
        // dd($blogs);
        return view('user.blog',['blogs'=>$blogs]);
    }
}
